package xiang.weiyu.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xiang.weiyu.common.OssConfig;
import xiang.weiyu.common.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 文件的上传与下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    /**
     * 文件上传
     *
     * @param file 参数名必须是这个
     * @return R<String>
     */
    @PostMapping
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException{
        //获得原始文件名,截取后缀名
        String OriginalFilename = file.getOriginalFilename();
        String houzhui = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));

        //生成新的文件名,UUID+后缀
        String filename = UUID.randomUUID().toString() + houzhui;

        //创建阿里云oss实例
        OSS ossClient = new OSSClientBuilder().build(OssConfig.ENDPOINT, OssConfig.KEY_ID, OssConfig.KEY_SECRET);

        try {
            // 创建PutObject请求。
            ossClient.putObject(OssConfig.BUCKET_NAME, "picture/" + filename, file.getInputStream());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return R.success(filename);
    }

    /**
     * 文件下载,图片上传后预览
     *
     * @param name     文件名
     * @param response 响应
     */
    @GetMapping
    @RequestMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException{
        //设置回传格式
        response.setContentType("image/jpeg");

        //创建阿里云oss实例
        OSS ossClient = new OSSClientBuilder().build(OssConfig.ENDPOINT, OssConfig.KEY_ID, OssConfig.KEY_SECRET);

        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(OssConfig.BUCKET_NAME, "picture/"+name);

        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();

        //输入流读取文件
        int len;
        byte[] bytes = new byte[1024];
        ServletOutputStream outputStream = response.getOutputStream();
        //输出流返回给页面
        while ((len = content.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        content.close();
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
